//
//  GMExamVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/11/16.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMExamVC.h"
#import "GMExamModel.h"
#import "GMSubjectsModel.h"
#import "GMExercisesCell.h"
#import "GMAnswerCardVC.h"
@interface GMExamVC ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UIButton *timeBtn;
@property (nonatomic, strong) ZJTimeCountDown *countDown;
@end

@implementation GMExamVC

-(void)viewWillAppear:(BOOL)animated{
    if(kIsEmptyObject(self.baseModel)){
        //如果没数据有请求数据
        [self getExaminationData];
    }else{
        kWeakObject(self)
        [weakself.countDown zj_timeCountDownWithSecondTime:self.baseModel.UsableTime completeBlock:^(NSInteger hour, NSInteger minute, NSInteger second) {
            [weakself.timeBtn setTitle:[NSString stringWithFormat:@"%02ld:%02ld:%02ld",hour,minute,second] forState:UIControlStateNormal];
            if (hour ==0 && minute ==0 && second ==0) {
                //如果倒计时等于0，就调用提交按钮
                [weakself sumbitAllAnser];
            }
        }];
        //有数据表明是继续答题，直接使用
        [self.dataArr removeAllObjects];
        [self.dataArr addObjectsFromArray:self.baseModel.Subjects];
        [self.collectionView reloadData];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"在线考试";
    self.view.backgroundColor = kWhiteColor;
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMExercisesCell" bundle:nil] forCellWithReuseIdentifier:@"GMExercisesCell"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"choseSelected" object:nil];
    _timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_timeBtn setTitle:@"00:00:00" forState:UIControlStateNormal];
    _timeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_timeBtn sizeToFit];
    UIBarButtonItem *informationCardItem = [[UIBarButtonItem alloc] initWithCustomView:_timeBtn];
    UIBarButtonItem *fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixedSpaceBarButtonItem.width = 5;
    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [settingBtn addTarget:self action:@selector(sumbitAllAnser) forControlEvents:UIControlEventTouchUpInside];
    [settingBtn setImage:[UIImage imageNamed:@"sumbit"] forState:UIControlStateNormal];
    [settingBtn sizeToFit];
    UIBarButtonItem *settingBtnItem = [[UIBarButtonItem alloc] initWithCustomView:settingBtn];
    self.navigationItem.rightBarButtonItems  = @[settingBtnItem,fixedSpaceBarButtonItem,informationCardItem];
    _countDown = [[ZJTimeCountDown alloc] init];
}
// @selector(receiveNotification:)方法， 即受到通知之后的事件
- (void)receiveNotification:(NSNotification *)noti{
    GMSubjectsModel *subModel = [GMSubjectsModel mj_objectWithKeyValues:noti.object];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:[subModel.SortNo integerValue]-1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionRight) animated:YES];
    });
    
}

-(void)getExaminationData{

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.resId forKey:@"resId"];
    [dict setValue:self.TestRoomId forKey:@"testRoomId"];
    [dict setValue:self.TestTimeId forKey:@"testTimeId"];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetTestData&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMExamModel *model = [GMExamModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                for (GMSubjectsModel *subModel in model.Subjects) {
                    subModel.examId = model.Id;
                }
                self.baseModel = model;
                kWeakObject(self)
                [weakself.countDown zj_timeCountDownWithSecondTime:model.UsableTime completeBlock:^(NSInteger hour, NSInteger minute, NSInteger second) {
                    [weakself.timeBtn setTitle:[NSString stringWithFormat:@"%02ld:%02ld:%02ld",hour,minute,second] forState:UIControlStateNormal];
                    if (hour ==0 && minute ==0 && second ==0) {
                        //如果倒计时等于0，就调用提交按钮
                        [weakself sumbitAllAnser];
                    }
                }];
                [self.dataArr removeAllObjects];
                [self.dataArr addObjectsFromArray:model.Subjects];
                [self.collectionView reloadData];
            }else{
                UIAlertController *alert  = [UIAlertController zj_alertControllerWithTitle:@"提示" message:[responseObject objectForKey:RESULT_NAME_Message] optionStyle:OptionStyleStyleOnlyOK OkTitle:@"好的" cancelTitle:@"" okBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                } cancelBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                }];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络出错" toView:self.view];
        }
    }];
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, -35, DEVICE_WIDTH, self.view.frame.size.height) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.pagingEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMExercisesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMExercisesCell" forIndexPath:indexPath];
    GMSubjectsModel *subModel = self.dataArr[indexPath.row];
    cell.model = subModel;
    cell.name = self.baseModel.Title;
    cell.index = indexPath.row+1;
    cell.total = self.baseModel.Count;
    /**下一题*/
    cell.nextBlock = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionRight) animated:YES];
        });
    };
    /**上一题*/
    cell.lastBlock = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
            [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionLeft) animated:YES];
        });
    };
    kWeakObject(self)
    /**提交所有答案*/
    cell.sumbitBlock = ^{
        [weakself sumbitAllAnser];
    };
    return cell;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
- (void)sumbitAllAnser{
    GMAnswerCardVC *vc = [[GMAnswerCardVC alloc] init];
    vc.baseModel = self.baseModel;
    [self.navigationController pushViewController:vc animated:YES];

}
-(void)dealloc{
    [_countDown zj_timeDestoryTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
